<template>
  <div class="the-map-component">
    <v-stage ref="ref-stage" :config="stageConfig">
      <v-layer>
        <v-image
          :config="{
          image:mapImage,
          width:mapSize,
          height:mapSize,
          opacity:0.7
        }"
        ></v-image>
        <!-- <v-rect
          :config="{
          x: 0,
          y: 0,
          width: 100,
          height: 100,
          fill: 'red',
          shadowBlur: 10
        }"
        />-->
      </v-layer>
      <v-layer ref="lines-layer"></v-layer>
    </v-stage>
    <hr />
    <br />
    <!-- <event-time></event-time> -->
  </div>
</template>

<script>
import axios from "axios";
import konva from "konva";
import Gradient from "javascript-color-gradient";
import * as Color from "color";
import { map, clamp, sortBy } from "lodash";
import EventTime from "./EventTime";

// const KonvaLayer = konva.Layer;
const DesertMap_SafetyZone_40000 =
  "http://m.tuniucdn.com/fb2/t1/G6/M00/EC/B9/Cii-TF743eWIArKuAACJdOT_iYEAANWTAP7h2EAAImM20.json";
const SavageMap_SafetyZone_30000 =
  "http://m.tuniucdn.com/fb2/t1/G6/M00/EC/BC/Cii-U1746sCIRYqrAACPbY1MhQUAANWUgG_syAAAI-F26.json";
const SavageMap_SafetyZone_20000 =
  "http://m.tuniucdn.com/fb2/t1/G6/M00/EC/BC/Cii-TF747OeIBy0rAACPQSUaqqkAANWVAMk1NgAAI9Z44.json";
const SavageMap_SafetyZone_20000_20210216 =
  "https://qimage.owhat.cn/prod/master/image/ca7f95f2-66d4-44d7-a990-4a4599767f4b";
const DesertMap_SafetyZone_40000_20210217 =
  "https://qimage.owhat.cn/prod/master/image/67701910-324f-45e1-aef1-c83a373c6e96";
const HaidaoMap_SafetyZone_40000_20210217 =
  "https://qimage.owhat.cn/prod/master/image/cd7789bf-8ff5-4ee5-bf45-045d57c4cc97";
const HaidaoMap_SafetyZone_40000_20210217v200m =
  "https://qimage.owhat.cn/prod/master/image/54e3ef6e-168f-4359-9c0b-57dc0eee48ce";
const VikendiMap_SafetyZone_40000_20210217 =
  "https://qimage.owhat.cn/prod/master/image/c4fe8031-32e5-4428-bd37-6906901ffa86";
const MAP_IMAGES = {
  Vikendi:
    "http://n1-q.mafengwo.net/s16/M00/1F/16/CoUBUl6J6-WAfTq9ABN1dkMMLI4971.jpg#DihorOtok_Main",
  "Erangel (Remastered)":
    "http://n1-q.mafengwo.net/s16/M00/24/CD/CoUBUl6J8CGAZ8FWACwGssFmNzs911.jpg#Baltic_Main.jpg.jpg",
  Miramar:
    "http://b1-q.mafengwo.net/s16/M00/25/07/CoUBUl6J8DuABPwhAB3VGbsEWx0692.jpg#Desert_Main.jpg.jpg",
  Erangel:
    "http://n1-q.mafengwo.net/s16/M00/25/14/CoUBUl6J8E-AbIDmABcvo6NWiPE512.jpg#Erangel_Main.jpg.jpg",
  Sanhok:
    "http://p1-q.mafengwo.net/s16/M00/25/2E/CoUBUl6J8HWAB3mbABe2H5mDyy8107.jpg#Savage_Main.jpg.jpg"
};
const MAP_LENGTH_CENTIMETERS = {
  Vikendi: 612000,
  "Erangel (Remastered)": 816000,
  Miramar: 816000,
  Erangel: 816000,
  Sanhok: 408000
};

const MAP_NAME = "Sanhok";

const toScale = (pubgMapSize, mapSize, n) =>
  (n / pubgMapSize) * mapSize * (pubgMapSize === 816000 ? 0.99609375 : 1);

const DRAW_MAP_SIZE = 1050;
export default {
  name: "SafetyzoneGridHeatmap",
  data() {
    return {
      mapSize: DRAW_MAP_SIZE,
      stageConfig: {
        width: DRAW_MAP_SIZE,
        height: DRAW_MAP_SIZE,
        draggable: true
      },
      mapName: MAP_NAME,
      mapImageLink: MAP_IMAGES[MAP_NAME],
      mapImage: (_ => {
        let img = new window.Image();
        img.src = MAP_IMAGES[MAP_NAME];
        return img;
      })(),
      mapScale: 1,
      offsetX: 0,
      offsetY: 0
    };
  },
  computed: {},
  components: {
    EventTime
  },
  async mounted() {
    let grids_data = await this.getRemoteData(
      SavageMap_SafetyZone_20000_20210216
    );
    let mapSize = DRAW_MAP_SIZE;
    let rawMapSize = MAP_LENGTH_CENTIMETERS[MAP_NAME];
    const _scale = mapSize / rawMapSize;
    // debugger;
    let grids_normal = (_ => {
      let rects = [];
      let max = grids_data.max_in_normal;
      let colorGradient = new Gradient();

      let color1 = "#0000FF"; //浅色
      // color1 = "#af2c2c";
      let color2 = "#000099"; //深色

      colorGradient.setGradient(color1, color2);
      colorGradient.setMidpoint(max - 1);

      let getColorByValue = n => {
        let hex_ = colorGradient.getColor(n);
        hex_ = hex_.replace("#", "");
        while (hex_.length < 6) {
          hex_ = "0" + hex_;
        }
        let hex = `#${hex_}`;
        // debugger;
        let c = new Color(hex);
        let rgba = c.alpha(n / max).toString();
        // debugger;
        return rgba;
      };

      for (let xi = 0; xi < grids_data.GRIDS_IN_NORMAL.length; xi++) {
        for (let yi = 0; yi < grids_data.GRIDS_IN_NORMAL[xi].length; yi++) {
          if (grids_data.GRIDS_IN_NORMAL[xi][yi] > 0) {
            let [x, y, width] = [
              xi * grids_data.GRID_LENGTH,
              yi * grids_data.GRID_LENGTH,
              grids_data.GRID_LENGTH
            ].map(e => e * _scale);
            let rect = new konva.Rect({
              x: x,
              y: y,
              width: width,
              height: width,
              fill: getColorByValue(grids_data.GRIDS_IN_NORMAL[xi][yi]),
              stroke: "rgba(0,0,0,1)",
              strokeWidth: 0.05
            });
            rects.push(rect);
          }
        }
      }
      return rects;
    })();
    let grids_small = (_ => {
      let rects = [];
      let max = grids_data.max_in_small;
      let colorGradient = new Gradient();
      // debugger;
      let color1 = "#0000FF"; //浅色
      // color1 = "#af2c2c";
      let color2 = "#000066"; //深色

      colorGradient.setGradient(color1, color2);
      colorGradient.setMidpoint(max - 1);

      let getColorByValue = n => {
        let hex_ = colorGradient.getColor(n);
        hex_ = hex_.replace("#", "");
        while (hex_.length < 6) {
          hex_ = "0" + hex_;
        }
        let hex = `#${hex_}`;
        // debugger;
        let c = new Color(hex);
        let rgba = c.alpha(n / max).toString();
        // debugger;
        return rgba;
      };

      for (let xi = 0; xi < grids_data.GRIDS_IN_SMALL.length; xi++) {
        for (let yi = 0; yi < grids_data.GRIDS_IN_SMALL[xi].length; yi++) {
          if (grids_data.GRIDS_IN_SMALL[xi][yi] > 0) {
            let [x, y, width] = [
              xi * grids_data.GRID_LENGTH,
              yi * grids_data.GRID_LENGTH,
              grids_data.GRID_LENGTH
            ].map(e => e * _scale);
            let rect = new konva.Rect({
              x: x,
              y: y,
              width: width,
              height: width,
              fill: getColorByValue(grids_data.GRIDS_IN_SMALL[xi][yi]),
              stroke: "rgba(0,0,0,1)",
              strokeWidth: 0.05
            });
            rects.push(rect);
          }
        }
      }
      return rects;
    })();

    // return;

    // debugger
    let v_layer = this.$refs["lines-layer"];
    /**@type {konva.Layer} */
    let layer = v_layer.getNode();
    // layer.add(...grids_normal);
    layer.add(...grids_small);
    layer.draw();

    const MIN_SCALE = 1;
    const MAX_SCALE = 50;
    let v_stage = this.$refs["ref-stage"];
    /**@type {konva.Stage} */
    let stage = v_stage.getNode();
    let v = this;

    let handleZoom =
      /**
       * @param {Number} scaleDelta
       * @param {Number} layerX?
       * @param {Number} layerY?
       */
      (scaleDelta, layerX, layerY) => {
        if (!layerX) layerX = DRAW_MAP_SIZE / 2;
        if (!layerY) layerY = DRAW_MAP_SIZE / 2;
        let newScale = clamp(v.mapScale * scaleDelta, MIN_SCALE, MAX_SCALE);
        let mousePointX = layerX / v.mapScale - v.offsetX / v.mapScale;
        let mousePointY = layerY / v.mapScale - v.offsetY / v.mapScale;
        let offsetX = -(mousePointX - layerX / newScale) * newScale;
        let offsetY = -(mousePointY - layerY / newScale) * newScale;
        offsetX = clamp(offsetX, -(newScale - 1) * DRAW_MAP_SIZE, 0);
        offsetY = clamp(offsetY, -(newScale - 1) * DRAW_MAP_SIZE, 0);
        // debugger
        v.mapScale = newScale;
        v.offsetX = offsetX;
        v.offsetY = offsetY;
        // debugger;
        stage.scaleX(newScale);
        stage.scaleY(newScale);
        stage.x(offsetX);
        stage.y(offsetY);
        stage.batchDraw();
      };
    stage.dragBoundFunc(pos => {
      // debugger;
      let { x, y } = pos;
      x = clamp(x, -(this.mapScale - 1) * DRAW_MAP_SIZE, 0);
      y = clamp(y, -(this.mapScale - 1) * DRAW_MAP_SIZE, 0);
      return {
        x,
        y
      };
    });
    stage.on("dragend", ev => {
      // debugger
      let x = ev.target.x();
      let y = ev.target.y();
      x = clamp(x, -(this.mapScale - 1) * DRAW_MAP_SIZE, 0);
      y = clamp(y, -(this.mapScale - 1) * DRAW_MAP_SIZE, 0);
      stage.x(x);
      stage.y(y);
      stage.batchDraw();
    });
    stage.on("wheel", ev => {
      console.log(ev);
      ev.evt.preventDefault();
      const scaleDelta = ev.evt.deltaY > 0 ? 1 / 1.2 : 1.2;
      handleZoom(scaleDelta, ev.evt.layerX, ev.evt.layerY);
    });
    // debugger;
  },
  methods: {
    getRemoteData(link) {
      return new Promise(resolve => {
        axios
          .get(link)
          .then(axresp => {
            resolve(axresp.data);
          })
          .catch(axerr => {
            debugger;
          });
      });
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
@mapSize: 800px;
.the-map-component {
  // display: flex;
  #map {
    width: @mapSize;
    height: @mapSize;
  }
  .h-check-players {
  }
}
</style>
